<template>
    <div class="app-container">
        <loading :loadingFlag="loadingFlag" :text="'文件上传中...'" />
        <div class="layout-content">
            <div class="cell_list">
                <div class="cell_item" v-for="(item, index) in taskList" :key="index">
                    <div class="tip" :style="{ backgroundColor: tipBgColor(item) }">
                        {{ tipText(item) }}
                    </div>
                    <h5>{{ item.itemName }}</h5>
                    <div class="cell_content">
                        <p>
                            <span>法规依据:</span><span>{{ item.accordanceStandard_dictText }}</span>
                        </p>
                        <p>
                            <span>样品信息:</span><span v-for="ite in item.limsProjectSampleList" :key="ite.sampleCode">{{
                                ite.sampleCode }} {{ ite.sampleName }}</span>
                        </p>
                        <p>
                            <span>试验设备:</span>
                            <span v-for="(ite, ind) in item.limsDeviceList" :key="ind">
                                {{ ite.deviceCode }} {{ ite.deviceName }}
                            </span>
                        </p>
                        <p>
                            <span>排程时间:</span><span>{{ formatTime(item.planStartDate) }} ~
                                {{ formatTime(item.planEndDate) }}</span>
                        </p>
                        <p>
                            <span>试验工程师:</span><span class="text" v-for="ite in item.userList" :key="ite.id">{{
                                ite.realname
                            }}</span>
                        </p>
                        <div class="control_class">
                            <van-button class="common" @click="handleStart(item)" :disabled="item.state === 'started' ||
                                item.state === 'paused' ||
                                item.state === 'finished'
                                " :class="{
        startActive: item.state === 'started',
    }">
                                开始
                            </van-button>
                            <van-button class="common" @click="handleEnd(item)" :disabled="item.state === 'finished'"
                                :class="{
                                    endActive: item.state === 'finished',
                                }">
                                结束
                            </van-button>
                            <van-button class="common" type="default" @click="questionEnter(item)">问题录入</van-button>
                            <van-button class="common" type="default" @click="originalrecord(item)">原始记录录入</van-button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <van-dialog class="origin_class" v-model="origintype" title="原始记录录入">
            <div class="origin_main">
                <div class="title">
                    <span>原始记录</span>
                </div>
                <van-uploader ref="uploader" style="width: 100%" :accept="''" :max-size="2 * 1024 * 1024 * 1024"
                    @oversize="onOversize" :after-read="(file) => {
                            recordApprovaAfterRead(file, 'originlist');
                        }
                        ">
                    <van-button size="small" style="width: 100px" type="primary">原始记录上传</van-button>
                </van-uploader>
                <div class="upload_content">
                    <div v-for="(item, index) in originlist" :key="index">
                        <div class="uc_item">
                            <p>{{ item.recordName }}</p>
                            <span>
                                <van-icon color="#1989fa" @click="deleteItem(item.id, originlist, 'originlist')"
                                    name="delete-o" />
                            </span>
                        </div>
                    </div>
                </div>
            </div>
            <div class="testphote_main">
                <div class="title">
                    <span>试验照片</span>
                </div>
                <van-uploader ref="uploader" style="width: 100%" :max-count="1" :accept="'image/*'"
                    :max-size="2 * 1024 * 1024 * 1024" @oversize="onOversize" :after-read="(file) => {
                            recordApprovaAfterRead(file, 'testphoto');
                        }
                        ">
                    <van-button size="small" style="width: 120px" type="primary">试验照片上传</van-button>
                </van-uploader>
                <div class="upload_content">
                    <div v-for="(item, index) in testphoto" :key="index">
                        <div class="uc_item">
                            <p>{{ item.recordName }}</p>
                            <span>
                                <van-icon color="#1989fa" @click="deleteItem(item.id, testphoto, 'testphoto')"
                                    name="delete-o" />
                            </span>
                        </div>
                    </div>
                </div>
            </div>
        </van-dialog>
        <!-- <div class="layout-footer">
      <TabBar :activeTab="1"></TabBar>
    </div> -->
    </div>
</template>

<script>
import { Toast } from "vant";
import { Notify } from "vant";
import { axios } from "@/utils/request";
import { formatDate } from "@/utils/util";
import { getAction, postAction } from "@/api/manage";
import loading from "../components/loading.vue";
import TabBar from "@/components/TabBar";
export default {
    components: { TabBar, loading },
    data () {
        return {
            model: {},
            loadingFlag: false,
            origintype: false,
            url: {
                limsProjectData: "lims/limsProjectData/list",
                projectList: "lims/limsProjectItem/list",
                edit: "/lims/limsProjectItem/edit",
                add: "/lims/limsProjectRecord/add",
                delete: "/lims/limsProjectRecord/delete",
            },
            uploadUrl: "sys/attachment/upload",
            formatDate,
            taskList: [],
            testphoto: [],
            originlist: [],
            tree: {},
        };
    },
    created () {
        this.getTask();
        // this.getlimsProjectData();
    },
    computed: {
        formatTime () {
            return function (time) {
                if (!time) return;
                return this.formatDate(time, "yyyy-MM-dd");
            };
        },
        tipText () {
            return function (record) {
                if (record.state === "not_start" || !record.state) {
                    return "未开始";
                } else if (record.state === "started") {
                    return "进行中";
                } else if (record.state === "paused") {
                    return "暂停中";
                } else if (record.state === "finished") {
                    return "已完成";
                }
            };
        },
        tipBgColor () {
            return function (record) {
                if (record.state === "not_start" || !record.state) {
                    return "#666666";
                } else if (record.state === "started") {
                    return "#ff9900";
                } else if (record.state === "paused") {
                    return "#ff0000";
                } else if (record.state === "finished") {
                    return "#008000";
                }
            };
        },
    },
    methods: {
        deleteItem (id, list, key) {
            console.log(id);
            console.log(list);
            getAction(this.url.delete, { id }).then((res) => {
                if (res.success) {
                    Notify({
                        type: "warning",
                        message: res.message,
                    });
                    this[key] = list.filter((item) => item.id != id);
                } else {
                    Notify({
                        type: "warning",
                        message: res.message,
                    });
                }
            });
        },
        getlimsProjectData () {
            let params = {
                itemId: this.model.id,
                hasQuery: true,
                pageNo: 1,
                pageSize: 1000,
            };
            return new Promise((resolve, reject) => {
                getAction(this.url.limsProjectData, params).then((res) => {
                    console.log(res);
                    if (res.success) {
                        // this.tree = res.result.records;
                        this.tree.originlist = res.result.records.find(
                            (item) => item.name == "原始记录"
                        ).id;
                        this.tree.testphoto = res.result.records.find(
                            (item) => item.name == "试验照片"
                        ).id;
                        resolve(res.result.records);
                    } else {
                        reject(res.message);
                    }
                });
            });
        },
        onOversize () {
            Toast("文件大小不能超过 500mb");
        },
        //文件上传
        recorUploadImg (file, type) {
            console.log(file, "file1");
            const formData = new FormData();
            formData.append("file", file.file);
            formData.append("biz", "temp");
            axios
                .post(this.uploadUrl, formData, {
                    "content-type": "multipart/form-data",
                })
                .then((res) => {
                    console.log(res);

                    if (res.success) {
                        this.loadingFlag = false;
                        let timestamp = new Date().getTime();
                        let params = {
                            projectRecordAddRequestList: [
                                {
                                    auditState: "draft",
                                    checkItems: this.model.itemName,
                                    dataId: this.tree[type],
                                    files: res.result.id,
                                    itemId: this.model.id,
                                    projectId: this.model.projectId,
                                    recordName: res.result.fileUploadName,
                                    recorder: this.$store.getters.userInfo.username,
                                    recordDate: formatDate(timestamp, "yyyy-MM-dd hh:mm:ss"),
                                },
                            ],
                        };
                        console.log(params, "params");
                        postAction(this.url.add, params).then((res) => {
                            if (res.success) {
                                params.projectRecordAddRequestList[0].id = res.result[0].id;
                                this[type].push(params.projectRecordAddRequestList[0]);
                                console.log(type);
                                console.log(this[type]);
                            } else {
                                Notify({
                                    type: "warning",
                                    message: res.message,
                                });
                            }
                        });

                        this.loadingFlag = false;
                    } else {
                        this.loadingFlag = false;
                        Notify({
                            type: "warning",
                            message: "上传失败",
                        });
                        file.status = "failed";
                        file.message = "上传失败";
                    }
                })
                .catch((err) => {
                    Notify({
                        type: "warning",
                        message: "上传失败",
                    });
                    file.status = "failed";
                    file.message = "上传失败";
                });
        },
        //文件上传
        recordApprovaAfterRead (file, type) {
            console.log(file, "file2");
            this.loadingFlag = true;
            if (file instanceof Array) {
                file.map((v) => {
                    v.status = "uploading";
                    v.message = "上传中...";
                    this.recorUploadImg(v, type);
                });
            } else {
                file.status = "uploading";
                file.message = "上传中...";
                this.recorUploadImg(file, type);
            }
        },
        //原始记录录入
        async originalrecord (item) {
            console.log(item);
            this.model = item;
            await this.getlimsProjectData();
            this.origintype = true;
        },
        questionEnter (item) {
            console.log(item);
            let params = {
                projectCode: item.projectCode,
                processKey: "lims_problem_edit",
            };
            console.log(params);
            this.$router.push({ path: "questionEnter", query: params });
        },
        handleEnd (record) {
            if (this.$route.query.preview) {
                // this.$message.error('查看状态不能结束项目')
                return;
            }
            if (record.state === "not_start" || !record.state) {
                Notify({ type: "warning", message: "未点击开始不能点击结束按钮" });

                return;
            }
            let params = {
                id: record.id,
                state: "finished",
            };
            postAction(this.url.edit, params).then((res) => {
                if (res.success) {
                    this.getTask();
                } else {
                    console.log(res);
                    Notify({ type: "warning", message: res.message });
                }
            });
        },

        handleStart (record) {
            let params = {
                id: record.id,
                state: "started",
            };
            if (this.$route.query.preview) {
                // this.$message.error('查看状态不能开始项目')
                return;
            }
            postAction(this.url.edit, params).then((res) => {
                if (res.success) {
                    this.getTask();
                } else {
                    Notify({ type: "warning", message: res.message });
                }
            });
        },
        getTask () {
            let params = {
                projectId: this.$route.query.id,
                relatedMe: 1,
            };
            getAction(this.url.projectList, params).then((res) => {
                if (res.success) {
                    this.taskList = res.result.map((item) => {
                        item = item.limsProjectItemVOList[0];
                        return item;
                    });
                    if (!this.taskList.length) {
                        Notify({ type: "warning", message: "当前任务暂无数据" });
                    }
                }
            });
        },
    },
};
</script>

<style lang="scss" scoped>
::v-deep {
    .van-dialog__content {
        max-height: 400px;
        overflow-y: auto;
    }

    .origin_class {

        .origin_main,
        .testphote_main {
            padding: 10px;
            margin-bottom: 20px;

            .title {
                margin-bottom: 5px;

                span {
                    font-size: 16px;
                }
            }

            .upload_content {
                min-height: 100px;

                .uc_item {
                    display: flex;
                    align-items: center;
                    margin-top: 10px;
                    width: 95%;
                    word-break: break-all;

                    p {
                        flex: 1;
                        padding-right: 3px;
                        display: -webkit-box;
                        -webkit-box-orient: vertical;
                        -webkit-line-clamp: 2;
                        overflow: hidden;
                        margin: 0;
                    }

                    span {
                        display: block;
                        width: 20px;
                        text-align: center;

                        .van-icon {
                            text-align: center;
                        }
                    }
                }
            }
        }

        // background: red;
        .van-uploader__input-wrapper {
            width: 100%;

            .van-button {
                width: 300px;
                border-radius: 5px;
            }

            // background: red;
        }
    }
}

.startActive {
    background-color: #2b579a;
    color: #fff;
}

.endActive {
    background-color: #008000;
    color: #fff;
}

.app-container {
    height: 100%;

    .van-loading {
        margin-top: 100px;
    }

    .layout-content {
        height: 100%;
        background-color: #f5f5f5;

        .cell_list {

            // margin: 0 10px;
            .cell_item {
                .common {
                    border: 1px solid #ccc;
                    font-size: 12px;
                    padding: 4px 14px;
                    margin-right: 4px;
                }

                position: relative;
                padding: 15px;
                background-color: #fff;
                margin-bottom: 10px;
                border-radius: 5px;

                // border: 1px solid #cccccc;
                .tip {
                    position: absolute;
                    left: -18px;
                    top: 9px;
                    width: 70px;
                    height: 20px;
                    color: #fff;
                    font-size: 10px;
                    text-align: center;
                    line-height: 20px;
                    transform: rotate(-45deg);
                }

                h5 {
                    font-size: 18px;
                    margin: 0;
                    margin-left: 30px;
                }

                .cell_content {
                    p {
                        margin: 0;
                        line-height: 32px;
                        font-size: 16px;
                        line-height: 22px;
                        margin: 12px 0;

                        span {
                            font-size: 16px;
                            color: #919191;
                            margin-right: 10px;
                        }
                    }
                }
            }
        }
    }
}
</style>
